#!/usr/bin/env python

# Copyright (c) 2009, Purdue University
# All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
# 
# Neither the name of the Purdue University nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""Update named tool for Roster"""


__copyright__ = 'Copyright (C) 2009, Purdue University'
__license__ = 'BSD'
__version__ = '0.15'


import os
import sys
import getpass
import datetime

from optparse import OptionParser

from roster_user_tools import cli_record_lib
from roster_user_tools import cli_common_lib
from roster_user_tools import roster_client_lib
from roster_user_tools.action_flags import Update
from roster_user_tools.data_flags import NamedGlobals


class Args(Update, NamedGlobals):
  pass


def UpdateConfiguration(options):
  handle = open(options.file, 'r')
  try:
    named_file = handle.read()
  finally:
    handle.close()
  roster_client_lib.RunFunction(u'MakeNamedConfGlobalOption',
                                options.username,
                                credfile=options.credfile,
                                args=[options.dns_server_set,
                                      named_file],
                                server_name=options.server)
  if( not options.quiet ):
    print 'ADDED NAMED_CONF_GLOBAL_OPTION: %s' % options.file

def main(args):
  """Collects command line arguments, checks ip addresses and adds records.

  Inputs:
    args: list of arguments from the command line
  """
  command = None
  if( args and not args[0].startswith('-') ):
    command = args.pop(0)
  usage = ('\n'
           '\n'
           'To list avalible named global configurations:\n'
           '\t%s list -d <dns-server-set>\n'
           '\n'
           'To dump a configuration:\n'
           '\t%s dump [-i <option-id> | (-d <dns-server-set> -t <timestamp>)]\n'
           '\tNote: If option-id is not specified, will use latest '
           'configuration.\n'
           '\n'
           'To edit a configuration:\n'
           '\t%s edit [-i <option-id> | (-d <dns-server-set> -t <timestamp>)]\n'
           '\tNote: If option-id is not specified, will use latest '
           'configuration.\n'
           'To update to an existing file:\n'
           '\t%s update -d <dns-server-set> [-f <file-name>]\n'
           '\n'
           'To revert a change:\n'
           '\t%s revert -d <dns-server-set> -i <option-id>\n' % tuple(
               [sys.argv[0] for x in range(5)]))
  args_instance = Args(command,
      ['edit', 'list', 'dump', 'revert', 'update'], args, usage)
  options = args_instance.options
  try:
    cli_common_lib_instance = cli_common_lib.CliCommonLib(options)
  except cli_common_lib.ArgumentError, e:
    print 'ERROR: %s' % e
    sys.exit(1)
  cli_record_lib_instance = cli_record_lib.CliRecordLib(cli_common_lib_instance)

  timestamp = options.timestamp
  if( options.option_id is not None ):
    options.option_id = int(options.option_id)
  if( options.timestamp is not None ):
    try:
      timestamp = datetime.datetime.strptime(options.timestamp,
                                             '%Y-%m-%d %H:%M:%S')
    except ValueError:
      cli_common_lib.DnsError('Timestamp incorrectly formatted.', 1)

  if( command == 'update' ):
    UpdateConfiguration(options)
    if( not options.keep_output ):
      os.remove(options.file)

  elif( command == 'list' ):
    named_options = roster_client_lib.RunFunction(
        u'ListNamedConfGlobalOptionsClient', options.username,
        credfile=options.credfile, kwargs={'option_id': options.option_id,
                                           'dns_server_set':
                                               options.dns_server_set,
                                           'timestamp': timestamp},
        server_name=options.server)['core_return']
    if( options.no_header ):
      print_list = []
    else:
      print_list = [['option_id', 'timestamp', 'dns_server_set']]
    for option in named_options:
      print_list.append([option['id'],
        datetime.datetime.strptime(option['timestamp'].value,
                                   "%Y%m%dT%H:%M:%S").strftime(
                                       '%Y-%m-%d %H:%M:%S'),
        option['dns_server_set_name']])
    print cli_common_lib_instance.PrintColumns(
        print_list, first_line_header=not options.no_header)

  elif( command in ['dump', 'edit'] ):
    if( options.option_id ):
      named_options = roster_client_lib.RunFunction(
          u'ListNamedConfGlobalOptionsClient', options.username,
          credfile=options.credfile, kwargs={'option_id': options.option_id,
                                             'dns_server_set':
                                                 options.dns_server_set,
                                             'timestamp': timestamp},
          server_name=options.server)['core_return']
      if( len(named_options) == 0 ):
        cli_common_lib.DnsError('No configurations found.', 1)
      elif( len(named_options) == 1 ):
        handle = open(options.file, 'w')
        try:
          handle.writelines(named_options[0]['options'])
        finally:
          handle.close()

        if( command == 'edit' ):
          return_code = cli_common_lib.EditFile(options.file)

          if( return_code == 0 ):
            UpdateConfiguration(options)
          else:
            cli_common_lib.DnsError('Error editing file.', 1)
          if( not options.keep_output ):
            os.remove(options.file)
        else:
          print 'Wrote file: %s' % options.file

      else:
        cli_common_lib.DnsError('Multiple configurations found. This could be '
                                'due to an internal error or arguments may be '
                                'too general.', 1)

    else:
      named_option = roster_client_lib.RunFunction(
          u'ListLatestNamedConfig', options.username,
          credfile=options.credfile, args=[options.dns_server_set],
          server_name=options.server)['core_return']
      if( named_option is None ):
        cli_common_lib.DnsError('No configurations found.', 1)
      handle = open(options.file, 'w')
      try:
        handle.writelines(named_option['options'])
      finally:
        handle.close()

      if( command == 'edit' ):
        return_code = cli_common_lib.EditFile(options.file)

        if( return_code == 0 ):
          UpdateConfiguration(options)
        else:
          cli_common_lib.DnsError('Error editing file.', 1)
        if( not options.keep_output ):
          os.remove(options.file)
      else:
        print 'Wrote file: %s' % options.file

  elif( command == 'revert' ):
    roster_client_lib.RunFunction(u'RevertNamedConfig', options.username,
        credfile=options.credfile, args=[options.dns_server_set,
                                         int(options.option_id)],
        server_name=options.server)
    if( not options.quiet ):
      print 'REVERTED NAMED_CONF_GLOBAL_OPTION: dns_server_set: %s rev: %s' % (
          options.dns_server_set, options.option_id)

  else:
    cli_common_lib.DnsError(
        'Command %s exists, but codepath does not.' % command, 1)

if __name__ == "__main__":
    main(sys.argv[1:])
